package com.xdy.server.core;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: XDY.
 * @Email: 2280944114@qq.com
 * @CreateTime: 2023-03-13  15:24
 * @Description: 配置文件解析处理器
 * @Version: 1.0
 */
public class WebHandler extends DefaultHandler {
    private List<ServletEntity> servletEntities;
    private List<MappingEntity> mappingEntities;

    private ServletEntity servletEntity;
    private MappingEntity mappingEntity;

    private String tag;

    private String propTag;

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        if ("web-app".equals(qName)){
            servletEntities = new ArrayList<>();
            mappingEntities = new ArrayList<>();
        }else if ("servlet".equals(qName)){
            servletEntity = new ServletEntity();
            tag = qName;
        }else if ("servlet-mapping".equals(qName)){
            mappingEntity = new MappingEntity();
            tag = qName;
        }else{
            propTag = qName;
        }
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        String content = new String(ch,start,length);
        if (!content.trim().equals("")){
            if ("servlet".equals(tag)){
                if ("servlet-name".equals(propTag))
                    servletEntity.setName(content);
                else if ("servlet-class".equals(propTag))
                    servletEntity.setClazz(content);
            } else if ("servlet-mapping".equals(tag)) {
                if ("servlet-name".equals(propTag))
                    mappingEntity.setName(content);
                else if ("url-pattern".equals(propTag))
                    mappingEntity.addPattern(content);
            }
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        if ("servlet".equals(qName)){
            servletEntities.add(servletEntity);
        }else if ("servlet-mapping".equals(qName)){
            mappingEntities.add(mappingEntity);
        }
    }

    public List<ServletEntity> getServletEntities() {
        return servletEntities;
    }

    public List<MappingEntity> getMappingEntities() {
        return mappingEntities;
    }
}
